package com.yimaxiaoerlang.rtc_kit.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AsyncPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.FragmentActivity;

import com.yimaxiaoerlang.rtc_lib.YMRLClient;
import com.yimaxiaoerlang.rtc_lib.YMVideoRoomHelper;
import com.yimaxiaoerlang.rtc_lib.YMVideoRoomHelperLinstener;
import com.yimaxiaoerlang.rtc_kit.R;
import com.yimaxiaoerlang.rtc_kit.model.CallOpera;
import com.yimaxiaoerlang.rtc_kit.model.CallUser;
import com.yimaxiaoerlang.rtc_kit.CallManager;
import com.yimaxiaoerlang.rtc_kit.utils.ImageUtils;

public class CallSingleActivity extends FragmentActivity implements YMVideoRoomHelperLinstener {
    private static final String TAG = "CallSingleActivity";
    private boolean call = false;
    private String tid = "";
    private String channel = "";
    private String name = "";
    private String userAvatar = "";
    private CallOpera callOpera;
    private YMVideoRoomHelper videoHelper;
    private SurfaceView localView;
    private SurfaceView remoteView;
    private RelativeLayout.LayoutParams bigParams;
    private RelativeLayout.LayoutParams smallParams;
    private boolean localSmall = true;
    private AsyncPlayer ringPlayer;
    private ImageView ivCancal;
    private ImageView ivReject;
    private ImageView ivAnswer;
    private ImageView ivHandup;
    private ImageView ivSwitch;
    private ImageView ivSpeaker;
    private ImageView ivIcon;
    private LinearLayout layoutRecive;
    private LinearLayout callLayout;
    private TextView tvHint;
    private LinearLayout layoutInfo;
    private LinearLayout layoutCalling;
    private RelativeLayout layout;
    private final long delayMillis = 500L;
    private CallUser curUser;

    public static void call(
            Activity activity,
            String tid,
            String channel,
            String name,
            String userAvatar,
            boolean call
    ) {
        Intent intent = new Intent(activity, CallSingleActivity.class);
        intent.putExtra("tid", tid);
        intent.putExtra("channel", channel);
        intent.putExtra("call", call);
        intent.putExtra("name", name);
        intent.putExtra("userAvatar", userAvatar);
        activity.startActivity(intent);
    }

    public static void receiveCall(
            Context application, String tid,
            String channel,
            String name,
            String userAvatar,
            boolean call
    ) {
        Intent intent = new Intent(application, CallSingleActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("tid", tid);
        intent.putExtra("channel", channel);
        intent.putExtra("call", call);
        intent.putExtra("name", name);
        intent.putExtra("userAvatar", userAvatar);
        application.startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN
        );
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_call_single);
        initView();
        initData();
        initHandupBroadcast();
        initRejectBroadcast();
        initAnswerBroadcast();
    }

    private void initView() {
        ivCancal = findViewById(R.id.iv_cancal);
        ivReject = findViewById(R.id.iv_reject);
        ivAnswer = findViewById(R.id.iv_answer);
        ivIcon = findViewById(R.id.iv_icon);
        layoutRecive = findViewById(R.id.layout_recive);
        callLayout = findViewById(R.id.call_layout);
        layoutInfo = findViewById(R.id.layout_info);
        layoutCalling = findViewById(R.id.layout_calling);
        layout = findViewById(R.id.layout);
        ivHandup = findViewById(R.id.iv_handup);
        ivSwitch = findViewById(R.id.iv_switch);
        ivSpeaker = findViewById(R.id.iv_speaker);
        tvHint = findViewById(R.id.tv_hint);

        ivCancal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (callOpera != null) {
                    callOpera.hangup(tid, false);
                }
                if (videoHelper != null) {
                    videoHelper.leave();
                }


                finish();
            }
        });
        ivReject.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (callOpera != null) {
                    callOpera.refuse(tid, false);
                }
                finish();
            }
        });
        ivAnswer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (callOpera != null) {
                    callOpera.answer(tid, channel, false);
                }
                if (videoHelper != null) {
                    videoHelper.join();
                }
                stopCallSound();
            }
        });
        ivHandup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (callOpera != null) {
                    callOpera.hangup(tid, false);
                }
                if (videoHelper != null) {
                    videoHelper.leave();
                }

                finish();
            }
        });
        ivSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (videoHelper != null) {
                    videoHelper.switchCamera();
                }
            }
        });

        ivSpeaker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (videoHelper != null) {
                    ivSpeaker.setImageResource(videoHelper.openSpeaker() ? R.mipmap.mianti_open : R.mipmap.mianti_close);

                }

            }
        });

        bigParams = new RelativeLayout.LayoutParams(-1, -1);
        smallParams = new RelativeLayout.LayoutParams(300, 500);
        smallParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        smallParams.setMargins(0, 20, 20, 0);

    }

    private void initData() {
        curUser = CallManager.getInstance().getCurUser();
        call = getIntent().getBooleanExtra("call", false);
        tid = getIntent().getStringExtra("tid");
        name = getIntent().getStringExtra("name") + "";
        userAvatar = getIntent().getStringExtra("userAvatar");
        channel = getIntent().getStringExtra("channel");

        initVideo();
        initCall();
        if (call) {
            showCall();
        } else {
            showRecive();
        }

    }

    /**
     * 初始化拨打
     */
    private void initCall() {
        callOpera = CallManager.getInstance().getCallOpera();
        ringPlayer = new AsyncPlayer("");
        startCallSound();
    }

    /**
     * 显示拨打
     */
    private void showCall() {
        ImageUtils.loadImage(ivIcon, userAvatar);
        layoutRecive.setVisibility(View.GONE);
        callLayout.setVisibility(View.VISIBLE);
        call();
    }

    /**
     * 显示接收
     */
    private void showRecive() {
        callLayout.setVisibility(View.GONE);
        layoutRecive.setVisibility(View.VISIBLE);
        ImageUtils.loadImage(ivIcon, userAvatar);
        tvHint.setText("对方邀请您进行视频通话");

    }

    /**
     * 显示接通中
     */
    private void showCalling() {
        layoutRecive.setVisibility(View.GONE);
        layoutInfo.setVisibility(View.GONE);
        callLayout.setVisibility(View.GONE);
        layoutCalling.setVisibility(View.VISIBLE);
    }

    /**
     * 拨打电话
     */
    private void call() {
        if (curUser != null && callOpera != null) {
            callOpera.call(
                    tid,
                    curUser.getNickname(),
                    curUser.getAvatar(),
                    channel
            );
            if (videoHelper != null) {
                videoHelper.join();

            }
            startCallSound();
        }

    }

    /**
     * 初始化视频
     */
    private void initVideo() {

        if (curUser != null) {
            videoHelper = new YMVideoRoomHelper(this, curUser.getUid().toString(), YMRLClient.getInstance().createChannel(channel), this);
            videoHelper.initLocal();
        }
    }


    /**
     * 开始播放音乐
     */
    private void startCallSound() {
//        val uri = Uri.parse(
//            "android.resource://" + App.INSTANCE.packageName
//                .toString() + "/" + R.raw.incoming_call_ring
//        )
//        ringPlayer.play(App.INSTANCE, uri, true, AudioManager.STREAM_RING)
    }

    /**
     * 停止播放音乐
     */
    private void stopCallSound() {
        ringPlayer.stop();
    }


    @Override
    public void onLocalJoin(SurfaceView surfaceViewRenderer) {
        Log.e(TAG, "onLocalJoin: 1" );
        localView = surfaceViewRenderer;
        localView.setLayoutParams(bigParams);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                layout.addView(surfaceViewRenderer, 0);
            }
        }, 100);
    }

    @Override
    public void onRemoteJoin(SurfaceView surfaceViewRenderer, String memberId) {
        showCalling();
        localView.setLayoutParams(smallParams);
        layout.removeView(localView);
        remoteView = surfaceViewRenderer;
        remoteView.setLayoutParams(bigParams);
        layout.addView(remoteView, 0);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                layout.addView(localView, 1);
            }
        }, delayMillis);

        //点击切换本地和远端视图
        localView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                switchPreview();
            }
        });
        if (remoteView != null) {
            remoteView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (!localSmall) {
                        switchPreview();
                    }
                }
            });
        }
    }

    public void onRemoteLeave(SurfaceView surfaceViewRenderer, String memberId) {
    }


    public void didReciveOtherMessage(String msg, String meberId) {

    }

    /**
     * 切换预览view
     */
    private void switchPreview() {
        if (localView == null || remoteView == null) return;
        //移除两个view重新添加
        layout.removeView(localView);
        layout.removeView(remoteView);
        if (localSmall) {

            if (localView != null) {
                localView.setLayoutParams(bigParams);
            }
            if (remoteView != null) {
                remoteView.setLayoutParams(smallParams);
            }
            layout.addView(localView, 0);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {

                    layout.addView(remoteView, 1);
                }
            }, delayMillis);

        } else {
            if (localView != null) {
                localView.setLayoutParams(smallParams);
            }
            if (remoteView != null) {
                remoteView.setLayoutParams(bigParams);
            }

            layout.addView(remoteView, 0);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {

                    layout.addView(localView, 1);
                }
            }, delayMillis);

        }
        localSmall = !localSmall;
    }

    private BroadcastReceiver handupBroadcastReceiver = new BroadcastReceiver() {
        @SuppressLint("NewApi")
        @Override
        public void onReceive(Context p0, Intent p1) {
            if (videoHelper != null) {
                videoHelper.leave();

            }

            Toast.makeText(p0, "对方挂断电话", Toast.LENGTH_SHORT).show();
            finish();
        }
    };

    /**
     * 挂断广播监听
     */
    private void initHandupBroadcast() {

        registerReceiver(handupBroadcastReceiver, new IntentFilter("handup"));
    }

    private BroadcastReceiver rejectBroadcastReceiver = new BroadcastReceiver() {
        @SuppressLint("NewApi")
        @Override
        public void onReceive(Context p0, Intent p1) {
            if (videoHelper != null) {
                videoHelper.leave();
            }
            Toast.makeText(p0, "对方拒绝接听", Toast.LENGTH_SHORT).show();
            finish();
        }
    };

    /**
     * 拒接广播监听
     */
    private void initRejectBroadcast() {

        registerReceiver(rejectBroadcastReceiver, new IntentFilter("reject"));
    }

    private BroadcastReceiver answerBroadcastReceiver = new BroadcastReceiver() {
        @SuppressLint("NewApi")
        @Override
        public void onReceive(Context p0, Intent p1) {
            stopCallSound();
        }
    };

    /**
     * 接听广播
     */
    private void initAnswerBroadcast() {

        registerReceiver(answerBroadcastReceiver, new IntentFilter("answer"));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopCallSound();
        unregisterReceiver(answerBroadcastReceiver);
        unregisterReceiver(rejectBroadcastReceiver);
        unregisterReceiver(handupBroadcastReceiver);
    }

}